import random
import threading
import time
from pynput.mouse import Listener as MouseListener, Button as MouseButton
from pynput.keyboard import Listener as KeyboardListener, Key

from win32_utils import click_mouse, is_shift_pressed, press_key, release_key, VK_SHIFT, switch_hotbar_slot

class ClickerCore:
    """
    自动点击器的核心逻辑：
    - 监听鼠标事件
    - 处理左键/右键/Shift的自动点击
    """
    
    CLICK_DURATION = 0.00813  # 每次点击消耗的时间（秒）
    
    def __init__(self, config_vars, mode_change_callback=None):
        # 配置变量
        self.left_long_press_time = config_vars['left_long_press_time']
        self.left_min_delay = config_vars['left_min_delay']
        self.left_max_delay = config_vars['left_max_delay']
        
        self.right_long_press_time = config_vars['right_long_press_time']
        self.right_min_delay = config_vars['right_min_delay']
        self.right_max_delay = config_vars['right_max_delay']
        
        self.shift_hold_time = config_vars['shift_hold_time']
        self.shift_interval = config_vars['shift_interval']
        self.enable_shift_click = config_vars['enable_shift_click']
        
        # 鱼竿连点配置
        self.fishing_mode_enabled = config_vars['fishing_mode_enabled']
        self.fishing_weapon_slot = config_vars['fishing_weapon_slot']
        self.fishing_rod_slot = config_vars['fishing_rod_slot']
        self.fishing_cast_min_delay = config_vars['fishing_cast_min_delay']
        self.fishing_cast_max_delay = config_vars['fishing_cast_max_delay']
        self.fishing_attack_min_count = config_vars['fishing_attack_min_count']
        self.fishing_attack_max_count = config_vars['fishing_attack_max_count']
        self.fishing_attack_min_delay = config_vars['fishing_attack_min_delay']
        self.fishing_attack_max_delay = config_vars['fishing_attack_max_delay']
        
        # 左键监控
        self.is_left_auto_clicking = False
        self.left_click_thread = None
        self.left_click_stop_event = threading.Event()
        self.left_press_time = 0
        
        # 右键监控
        self.is_right_auto_clicking = False
        self.right_click_thread = None
        self.right_click_stop_event = threading.Event()
        
        # Shift连点
        self.is_shift_mode = False
        self.shift_thread = None
        self.shift_stop_event = threading.Event()
        
        # 右键+中键判断
        self.right_pressed = False
        self.middle_pressed = False
        self.right_and_middle_press_time = None
        
        # 监听器
        self.is_listening = False
        self.mouse_listener = None
        self.keyboard_listener = None
        self.listener_lock = threading.Lock()
        
        # 鱼竿连点模式状态 (通过Z键切换)
        self.current_fishing_mode = False
        
        # GUI回调函数
        self.mode_change_callback = mode_change_callback
        
        # 线程清理器
        self.cleanup_threads = []
        self.cleanup_lock = threading.Lock()
    
    def start_listening(self):
        """开始监听鼠标和键盘事件"""
        with self.listener_lock:
            if (self.mouse_listener and self.mouse_listener.is_alive()) or \
               (self.keyboard_listener and self.keyboard_listener.is_alive()):
                return False
            
            try:
                # 启动鼠标监听器
                self.mouse_listener = MouseListener(on_click=self.on_click)
                self.mouse_listener.start()
                
                # 启动键盘监听器
                self.keyboard_listener = KeyboardListener(on_press=self.on_key_press)
                self.keyboard_listener.start()
                
                self.is_listening = True
                print("鼠标和键盘监听器已启动")
                
                # 启动线程清理器
                self._start_cleanup_thread()
                return True
            except Exception as e:
                print(f"无法启动监听器: {e}")
                return False
    
    def _start_cleanup_thread(self):
        """启动后台线程清理器，定期清理已停止的线程"""
        cleanup_thread = threading.Thread(target=self._cleanup_stopped_threads, daemon=True)
        cleanup_thread.start()
    
    def _cleanup_stopped_threads(self):
        """定期检查并清理已停止的线程"""
        while self.is_listening:
            # 清理已完成的线程
            with self.cleanup_lock:
                for thread in self.cleanup_threads[:]:
                    if not thread.is_alive():
                        self.cleanup_threads.remove(thread)
            # 每秒检查一次
            time.sleep(1)
    
    def _add_thread_for_cleanup(self, thread):
        """将线程添加到清理列表"""
        with self.cleanup_lock:
            self.cleanup_threads.append(thread)
    
    def stop_listening(self):
        """停止监听鼠标和键盘事件"""
        with self.listener_lock:
            try:
                # 停止鼠标监听器
                if self.mouse_listener and self.mouse_listener.is_alive():
                    self.mouse_listener.stop()
                    cleanup_thread = threading.Thread(
                        target=lambda: self.mouse_listener.join(timeout=0.5),
                        daemon=True
                    )
                    cleanup_thread.start()
                
                # 停止键盘监听器
                if self.keyboard_listener and self.keyboard_listener.is_alive():
                    self.keyboard_listener.stop()
                    cleanup_thread = threading.Thread(
                        target=lambda: self.keyboard_listener.join(timeout=0.5),
                        daemon=True
                    )
                    cleanup_thread.start()
                    
                print("监听器正在停止")
                self.mouse_listener = None
                self.keyboard_listener = None
                self.is_listening = False
                
                # 异步停止所有自动点击
                self._async_stop_all_clicking()
                return True
            except Exception as e:
                print(f"无法停止监听器: {e}")
                return False
    
    def _async_stop_all_clicking(self):
        """异步停止所有点击，不阻塞UI线程"""
        # 设置所有停止事件
        self.left_click_stop_event.set()
        self.right_click_stop_event.set()
        self.shift_stop_event.set()
        
        # 标记状态为已停止（不等待线程真正结束）
        self.is_left_auto_clicking = False
        self.is_right_auto_clicking = False
        self.is_shift_mode = False
        
        print("已发送所有停止信号")
    
    def on_key_press(self, key):
        """键盘按键事件处理"""
        try:
            # 获取按键字符
            key_str = None
            if hasattr(key, 'char') and key.char:
                key_str = key.char.lower()
            
            # 检测Z键切换鱼竿模式或终止鱼竿连点
            if key_str == 'z':
                # 如果当前正在鱼竿连点模式下运行，则终止连点
                if self.fishing_mode_enabled.get() and self.is_left_auto_clicking:
                    print("通过Z键终止鱼竿连点")
                    self._async_stop_left()
                else:
                    # 否则切换模式
                    new_mode = not self.fishing_mode_enabled.get()
                    mode_text = "鱼竿连点" if new_mode else "普通左键连点"
                    print(f"切换到 {mode_text} 模式")
                    
                    # 通知GUI更新状态
                    if self.mode_change_callback:
                        try:
                            self.mode_change_callback(new_mode)
                        except Exception as e:
                            print(f"GUI回调异常: {e}")
            
            # 检测X键也可以终止鱼竿连点（兼容性）
            elif key_str == 'x':
                if self.fishing_mode_enabled.get() and self.is_left_auto_clicking:
                    print("通过X键终止鱼竿连点")
                    self._async_stop_left()
                    
        except Exception as e:
            print(f"on_key_press 异常: {e}")
    
    def on_click(self, x, y, button, pressed):
        """
        鼠标点击事件处理
        - 左键：长按松开后 -> 启动左键连点
        - 右键 + 中键：长按松开后 -> 启动右键连点
          若 Shift 正在按住 + 用户开启了Shift连点，则为 Shift 模式
        """
        try:
            if button == MouseButton.left:
                if pressed:
                    # 若右键/shift正在连点，左键按下则先停止它们
                    if self.is_right_auto_clicking or self.is_shift_mode:
                        self._async_stop_right_and_shift()
                    self.left_press_time = time.time()
                else:
                    duration = time.time() - self.left_press_time
                    if duration >= self.left_long_press_time.get():
                        # 启动左键前先停右键/shift
                        self._async_stop_right_and_shift()
                        # 根据当前模式启动对应的连点
                        # 现在fishing_mode_enabled和current_fishing_mode是同一个概念
                        if self.fishing_mode_enabled.get():
                            self.start_fishing_auto_click()
                        else:
                            self.start_left_auto_click()

            elif button == MouseButton.right:
                if pressed:
                    # 若左键在连点，判断是否为鱼竿模式
                    if self.is_left_auto_clicking:
                        # 如果不是鱼竿连点模式，才停止左键连点
                        if not self.fishing_mode_enabled.get():
                            self._async_stop_left()

                    self.right_pressed = True
                    if self.middle_pressed:
                        self.right_and_middle_press_time = time.time()
                else:
                    self.right_pressed = False
                    if self.middle_pressed and self.right_and_middle_press_time is not None:
                        duration = time.time() - self.right_and_middle_press_time
                        if duration >= self.right_long_press_time.get():
                            # 若左键在连点，判断是否为鱼竿模式
                            if self.is_left_auto_clicking:
                                # 如果不是鱼竿连点模式，才停止左键连点
                                if not self.fishing_mode_enabled.get():
                                    self._async_stop_left()
                            else:
                                # 如果左键没在连点，则正常停止
                                self._async_stop_left()
                            # 判断Shift是否按下 + 是否启用
                            if is_shift_pressed() and self.enable_shift_click.get():
                                self.start_right_auto_click(shifted=True)
                            else:
                                self.start_right_auto_click(shifted=False)
                    self.right_and_middle_press_time = None

            elif button == MouseButton.middle:
                if pressed:
                    self.middle_pressed = True
                    if self.right_pressed:
                        self.right_and_middle_press_time = time.time()
                else:
                    self.middle_pressed = False
                    if self.right_pressed and self.right_and_middle_press_time is not None:
                        duration = time.time() - self.right_and_middle_press_time
                        if duration >= self.right_long_press_time.get():
                            # 若左键在连点，判断是否为鱼竿模式
                            if self.is_left_auto_clicking:
                                # 如果不是鱼竿连点模式，才停止左键连点
                                if not self.fishing_mode_enabled.get():
                                    self._async_stop_left()
                            else:
                                # 如果左键没在连点，则正常停止
                                self._async_stop_left()
                            # 判断Shift是否按下 + 是否启用
                            if is_shift_pressed() and self.enable_shift_click.get():
                                self.start_right_auto_click(shifted=True)
                            else:
                                self.start_right_auto_click(shifted=False)
                    self.right_and_middle_press_time = None

        except Exception as e:
            print(f"on_click 异常: {e}")
    
    def _async_stop_left(self):
        """异步停止左键连点"""
        if not self.is_left_auto_clicking:
            return
        self.left_click_stop_event.set()
        self.is_left_auto_clicking = False
    
    def _async_stop_right_and_shift(self):
        """异步停止右键和Shift连点"""
        if not self.is_right_auto_clicking and not self.is_shift_mode:
            return
        self.right_click_stop_event.set()
        self.shift_stop_event.set()
        self.is_right_auto_clicking = False
        self.is_shift_mode = False
    
    # ------------------ 左键连点 ------------------
    def start_left_auto_click(self):
        """启动左键自动点击"""
        if self.is_left_auto_clicking:
            return
        
        # 清理旧的停止事件并创建新的
        self.left_click_stop_event.clear()
        
        # 先设置状态再启动线程
        self.is_left_auto_clicking = True
        
        # 启动新线程
        self.left_click_thread = threading.Thread(target=self.left_auto_click, daemon=True)
        self.left_click_thread.start()
        print("开始左键自动点击线程")

    def stop_left_auto_click(self):
        """停止左键自动点击"""
        if not self.is_left_auto_clicking:
            return
            
        # 设置停止事件
        self.left_click_stop_event.set()
        
        # 立即将状态设为False，不等待线程结束
        self.is_left_auto_clicking = False
        
        # 异步清理线程（不阻塞UI）
        if self.left_click_thread and self.left_click_thread.is_alive():
            self._add_thread_for_cleanup(self.left_click_thread)
            
        print("停止左键自动点击线程")

    def left_auto_click(self):
        """左键自动点击线程"""
        print("左键自动点击线程已启动")
        try:
            while not self.left_click_stop_event.is_set():
                # 检查停止标志
                if self.left_click_stop_event.is_set():
                    break
                    
                click_mouse(button='left')
                
                # 获取随机延迟
                random_delay = random.uniform(self.left_min_delay.get(), self.left_max_delay.get())
                
                # 分段sleep，提高响应性
                self._sleep_with_check(random_delay, self.left_click_stop_event)
        except Exception as e:
            print(f"left_auto_click 异常: {e}")
        finally:
            self.is_left_auto_clicking = False
            print("左键自动点击线程结束")
    
    def _sleep_with_check(self, delay, stop_event, step=0.01):
        """分段sleep，提高对停止信号的响应速度"""
        end_time = time.time() + delay
        while time.time() < end_time:
            if stop_event.is_set():
                return
            # 剩余时间或步长，取较小值
            remaining = min(end_time - time.time(), step)
            if remaining <= 0:
                break
            time.sleep(remaining)
    
    # ------------------ 右键连点 ------------------
    def start_right_auto_click(self, shifted=False):
        """启动右键自动点击，可选是否使用Shift模式"""
        if self.is_right_auto_clicking or self.is_shift_mode:
            return

        # 清理旧的停止事件
        self.right_click_stop_event.clear()
        if shifted:
            self.shift_stop_event.clear()

        # 设置状态
        self.is_shift_mode = shifted
        self.is_right_auto_clicking = True

        # 启动右键连点线程
        self.right_click_thread = threading.Thread(target=self.right_auto_click, daemon=True)
        self.right_click_thread.start()

        # 若是shift模式，则启动shift线程
        if shifted:
            self.shift_thread = threading.Thread(target=self.shift_auto_click, daemon=True)
            self.shift_thread.start()

        print(f"开始右键自动点击线程 (shifted={shifted})")

    def stop_right_auto_click(self):
        """停止右键自动点击"""
        if not self.is_right_auto_clicking:
            return
            
        # 设置停止事件
        self.right_click_stop_event.set()
        
        # 立即将状态设为False
        self.is_right_auto_clicking = False
        
        # 异步清理线程
        if self.right_click_thread and self.right_click_thread.is_alive():
            self._add_thread_for_cleanup(self.right_click_thread)
            
        print("停止右键自动点击线程")

        if self.is_shift_mode:
            self.stop_shift_click()

    def right_auto_click(self):
        """右键自动点击线程"""
        print("右键自动点击线程已启动")
        try:
            while not self.right_click_stop_event.is_set():
                # 再次检查停止标志
                if self.right_click_stop_event.is_set():
                    break
                    
                click_mouse(button='right')
                
                # 获取随机延迟
                random_delay = random.uniform(self.right_min_delay.get(), self.right_max_delay.get())
                
                # 分段sleep
                self._sleep_with_check(random_delay, self.right_click_stop_event)
        except Exception as e:
            print(f"right_auto_click 异常: {e}")
        finally:
            self.is_right_auto_clicking = False
            print("右键自动点击线程结束")
    
    # ------------------ Shift 连点（固定间隔） ------------------
    def stop_shift_click(self):
        """停止Shift连点"""
        if not self.is_shift_mode:
            return
            
        # 设置停止事件
        self.shift_stop_event.set()
        
        # 立即将状态设为False
        self.is_shift_mode = False
        
        # 异步清理线程
        if self.shift_thread and self.shift_thread.is_alive():
            self._add_thread_for_cleanup(self.shift_thread)
            
        print("停止 Shift 连点线程")

    def shift_auto_click(self):
        """Shift连点线程"""
        print("Shift 连点线程已启动")
        try:
            while not self.shift_stop_event.is_set():
                # 再次检查停止标志
                if self.shift_stop_event.is_set():
                    break
                    
                # 1. 按住Shift
                press_key(VK_SHIFT)
                
                # 分段检查的sleep
                self._sleep_with_check(self.shift_hold_time.get(), self.shift_stop_event)
                
                # 检查是否需要停止
                if self.shift_stop_event.is_set():
                    release_key(VK_SHIFT)
                    break
                    
                release_key(VK_SHIFT)

                # 2. 等待固定间隔
                self._sleep_with_check(self.shift_interval.get(), self.shift_stop_event)

        except Exception as e:
            print(f"shift_auto_click 异常: {e}")
        finally:
            # 确保释放Shift键
            release_key(VK_SHIFT)
            self.is_shift_mode = False
            print("Shift 连点线程结束")
    
    def validate_configs(self):
        """验证配置有效性"""
        try:
            # 左键
            if self.left_long_press_time.get() <= 0:
                raise ValueError("左键长按时间必须大于0")
            if self.left_min_delay.get() < 0 or self.left_max_delay.get() < 0:
                raise ValueError("左键延迟时间不能为负数")
            if self.left_min_delay.get() > self.left_max_delay.get():
                raise ValueError("左键最小延迟不能大于最大延迟")

            # 右键
            if self.right_long_press_time.get() <= 0:
                raise ValueError("右键长按时间必须大于0")
            if self.right_min_delay.get() < 0 or self.right_max_delay.get() < 0:
                raise ValueError("右键延迟时间不能为负数")
            if self.right_min_delay.get() > self.right_max_delay.get():
                raise ValueError("右键最小延迟不能大于最大延迟")

            # Shift
            if self.shift_hold_time.get() < 0 or self.shift_interval.get() < 0:
                raise ValueError("Shift 配置不能为负数")
            
            # 鱼竿连点配置验证
            if self.fishing_mode_enabled.get():
                weapon_slot = self.fishing_weapon_slot.get()
                rod_slot = self.fishing_rod_slot.get()
                
                if not (1 <= weapon_slot <= 9):
                    raise ValueError("武器位必须在1-9之间")
                if not (1 <= rod_slot <= 9):
                    raise ValueError("鱼竿位必须在1-9之间")
                if weapon_slot == rod_slot:
                    raise ValueError("武器位和鱼竿位不能相同")
                    
                if self.fishing_cast_min_delay.get() < 0 or self.fishing_cast_max_delay.get() < 0:
                    raise ValueError("抛竿延迟时间不能为负数")
                if self.fishing_cast_min_delay.get() > self.fishing_cast_max_delay.get():
                    raise ValueError("抛竿最小延迟不能大于最大延迟")
                    
                if self.fishing_attack_min_delay.get() < 0 or self.fishing_attack_max_delay.get() < 0:
                    raise ValueError("攻击延迟时间不能为负数")
                if self.fishing_attack_min_delay.get() > self.fishing_attack_max_delay.get():
                    raise ValueError("攻击最小延迟不能大于最大延迟")
                    
                if self.fishing_attack_min_count.get() <= 0:
                    raise ValueError("最小攻击次数必须大于0")
                if self.fishing_attack_max_count.get() <= 0:
                    raise ValueError("最大攻击次数必须大于0")
                if self.fishing_attack_min_count.get() > self.fishing_attack_max_count.get():
                    raise ValueError("最小攻击次数不能大于最大攻击次数")

            return True
        except Exception as e:
            print(f"配置验证错误: {e}")
            return False, str(e)
    
    def calculate_frequency_ranges(self):
        """计算点击频率范围"""
        result = {}
        
        # 左键
        try:
            min_d = self.left_min_delay.get()
            max_d = self.left_max_delay.get()
            if min_d < 0 or max_d < 0:
                left_freq_text = "延迟不可为负"
            elif min_d > max_d:
                left_freq_text = "最小延迟>最大延迟"
            else:
                if max_d + self.CLICK_DURATION > 0:
                    min_freq = 1 / (max_d + self.CLICK_DURATION)
                else:
                    min_freq = float('inf')
                if min_d + self.CLICK_DURATION > 0:
                    max_freq = 1 / (min_d + self.CLICK_DURATION)
                else:
                    max_freq = float('inf')
                min_freq = round(min_freq, 2) if min_freq != float('inf') else "∞"
                max_freq = round(max_freq, 2) if max_freq != float('inf') else "∞"
                left_freq_text = f"{min_freq} ~ {max_freq}"
            result["left"] = left_freq_text
        except:
            result["left"] = "错误"

        # 右键
        try:
            min_d = self.right_min_delay.get()
            max_d = self.right_max_delay.get()
            if min_d < 0 or max_d < 0:
                right_freq_text = "延迟不可为负"
            elif min_d > max_d:
                right_freq_text = "最小延迟>最大延迟"
            else:
                if max_d + self.CLICK_DURATION > 0:
                    min_freq = 1 / (max_d + self.CLICK_DURATION)
                else:
                    min_freq = float('inf')
                if min_d + self.CLICK_DURATION > 0:
                    max_freq = 1 / (min_d + self.CLICK_DURATION)
                else:
                    max_freq = float('inf')
                min_freq = round(min_freq, 2) if min_freq != float('inf') else "∞"
                max_freq = round(max_freq, 2) if max_freq != float('inf') else "∞"
                right_freq_text = f"{min_freq} ~ {max_freq}"
            result["right"] = right_freq_text
        except:
            result["right"] = "错误"
            
        return result
    
    # ------------------ 鱼竿连点 ------------------
    def start_fishing_auto_click(self):
        """启动鱼竿连点模式"""
        if self.is_left_auto_clicking:
            return
        
        # 验证配置
        if not self._validate_fishing_config():
            print("鱼竿连点配置验证失败")
            return
        
        # 清理旧的停止事件并创建新的
        self.left_click_stop_event.clear()
        
        # 先设置状态再启动线程
        self.is_left_auto_clicking = True
        
        # 启动新线程
        self.left_click_thread = threading.Thread(target=self.fishing_auto_click, daemon=True)
        self.left_click_thread.start()
        print("开始鱼竿连点线程")
    
    def _validate_fishing_config(self):
        """验证鱼竿连点配置"""
        try:
            weapon_slot = self.fishing_weapon_slot.get()
            rod_slot = self.fishing_rod_slot.get()
            
            # 检查物品栏位置范围
            if not (1 <= weapon_slot <= 9):
                print("武器位必须在1-9之间")
                return False
            if not (1 <= rod_slot <= 9):
                print("鱼竿位必须在1-9之间")
                return False
            if weapon_slot == rod_slot:
                print("武器位和鱼竿位不能相同")
                return False
                
            # 检查延迟配置
            if self.fishing_cast_min_delay.get() < 0 or self.fishing_cast_max_delay.get() < 0:
                print("抛竿延迟不能为负数")
                return False
            if self.fishing_cast_min_delay.get() > self.fishing_cast_max_delay.get():
                print("抛竿最小延迟不能大于最大延迟")
                return False
                
            if self.fishing_attack_min_delay.get() < 0 or self.fishing_attack_max_delay.get() < 0:
                print("攻击延迟不能为负数")
                return False
            if self.fishing_attack_min_delay.get() > self.fishing_attack_max_delay.get():
                print("攻击最小延迟不能大于最大延迟")
                return False
                
            if self.fishing_attack_min_count.get() <= 0:
                print("最小攻击次数必须大于0")
                return False
            if self.fishing_attack_max_count.get() <= 0:
                print("最大攻击次数必须大于0")
                return False
            if self.fishing_attack_min_count.get() > self.fishing_attack_max_count.get():
                print("最小攻击次数不能大于最大攻击次数")
                return False
                
            return True
        except Exception as e:
            print(f"鱼竿配置验证异常: {e}")
            return False
    
    def fishing_auto_click(self):
        """鱼竿连点线程"""
        print("鱼竿连点线程已启动")
        try:
            while not self.left_click_stop_event.is_set():
                # 检查停止标志
                if self.left_click_stop_event.is_set():
                    break
                
                # 第一步：切换到鱼竿位
                print("切换到鱼竿位")
                switch_hotbar_slot(self.fishing_rod_slot.get())
                
                # 短暂延迟确保切换成功
                self._sleep_with_check(0.1, self.left_click_stop_event)
                if self.left_click_stop_event.is_set():
                    break
                
                # 第二步：右键抛竿
                print("抛竿")
                click_mouse(button='right')
                
                # 第三步：等待抛竿延迟
                cast_delay = random.uniform(self.fishing_cast_min_delay.get(), self.fishing_cast_max_delay.get())
                print(f"等待 {cast_delay:.2f} 秒")
                self._sleep_with_check(cast_delay, self.left_click_stop_event)
                if self.left_click_stop_event.is_set():
                    break
                
                # 第四步：切换到武器位
                print("切换到武器位")
                switch_hotbar_slot(self.fishing_weapon_slot.get())
                
                # 短暂延迟确保切换成功
                self._sleep_with_check(0.1, self.left_click_stop_event)
                if self.left_click_stop_event.is_set():
                    break
                
                # 第五步：执行攻击
                attack_count = random.randint(self.fishing_attack_min_count.get(), self.fishing_attack_max_count.get())
                print(f"开始攻击 {attack_count} 次")
                for i in range(attack_count):
                    if self.left_click_stop_event.is_set():
                        break
                    
                    click_mouse(button='left')
                    
                    # 攻击间延迟（除了最后一次）
                    if i < attack_count - 1:
                        attack_delay = random.uniform(self.fishing_attack_min_delay.get(), 
                                                    self.fishing_attack_max_delay.get())
                        self._sleep_with_check(attack_delay, self.left_click_stop_event)
                
                # 循环继续（重新抛竿）
                
        except Exception as e:
            print(f"fishing_auto_click 异常: {e}")
        finally:
            self.is_left_auto_clicking = False
            print("鱼竿连点线程结束") 